﻿@page "/groups"
@layout SimpleIdServer.IdServer.Website.Shared.MainLayout
@attribute [Authorize("Authenticated")]
@inject IState<SearchGroupsState> searchGroupsState
@inject IDispatcher dispatcher
@inject NotificationService notificationService
@inject ContextMenuService contextMenuService
@inject IUrlHelper urlHelper
@inject DialogService dialogService
@inherits Fluxor.Blazor.Web.Components.FluxorComponent
@using SimpleIdServer.IdServer.Website.Resources;
@using SimpleIdServer.IdServer.Website.Shared.Dialogs
@using SimpleIdServer.IdServer.Website.Stores.GroupStore;
@using SimpleIdServer.IdServer.Website.Stores.RealmStore;


<SidAuthorizeView Roles=@("/groups/manage,/groups/view")>
    <Authorized>
        <div class="row">
            <div class="col">
                <RadzenText class="mt-3 mb-3 no-margin" Text="Groups" TextStyle="TextStyle.DisplayH3" />
                <p>
                    @Global.RolesDescription
                </p>
            </div>
            <div class="col-3">
                <SidAuthorizeView Roles=@("/groups/manage")>
                    <Authorized>
                        <RadzenButton class="mb-1" Click="@(args => AddGroup())" Icon="add" Text="@Global.AddGroup" ButtonStyle="ButtonStyle.Primary" Size="ButtonSize.Medium"></RadzenButton>
                    </Authorized>
                </SidAuthorizeView>
            </div>
        </div>

        <RadzenDataGrid @ref="groupsGrid"
                        AllowFiltering="true"
                        AllowColumnResize="true"
                        AllowAlternatingRows="false"
                        AllowSorting="true"
                        PageSize="30"
                        AllowPaging="true"
                        FilterMode="FilterMode.Simple"
                        LogicalFilterOperator="LogicalFilterOperator.And"
                        FilterCaseSensitivity=FilterCaseSensitivity.CaseInsensitive
                        PagerHorizontalAlign="HorizontalAlign.Left"
                        ShowPagingSummary="true"
                        IsLoading="@searchGroupsState.Value.IsLoading"
                        Count="@searchGroupsState.Value.Count"
                        Data="@searchGroupsState.Value.Groups"
                        LoadData="@LoadData"
                        RowRender="@RowRender"
                        TItem="SelectableGroup"
                        ColumnWidth="300px">
            <Columns>
                <RadzenDataGridColumn TItem="SelectableGroup" Filterable="false" Sortable="false" Width="80px" TextAlign="TextAlign.Center">
                    <HeaderTemplate>
                        <RadzenCheckBox @bind-Value=@selectAll Change="@(args => ToggleAll(args))" TValue="bool" />
                    </HeaderTemplate>
                    <Template Context="data">
                        <RadzenCheckBox @bind-Value=@data.IsSelected Change="@(args => ToggleChanged(args, data))" TValue="bool" />
                    </Template>
                </RadzenDataGridColumn>
                <RadzenDataGridColumn TItem="SelectableGroup" Filterable="true" Property="Group.Name" Sortable="true" Title="@Global.Name" Width="80px">
                    <Template Context="data">
                        <RadzenLink Text="@data.Group.Name" Path="@(urlHelper.GetUrl($"/groups/{data.Group.Id}/children"))" />
                    </Template>
                </RadzenDataGridColumn>
                <RadzenDataGridColumn TItem="SelectableGroup" Property="Group.Description" Filterable="true" Sortable="false" Title="@Global.Description" Width="80px" />
                <RadzenDataGridColumn TItem="SelectableGroup" Property="Group.Source" Filterable="true" Sortable="false" Title="@Global.Source" Width="80px">
                    <Template Context="data">
                        @if (!string.IsNullOrWhiteSpace(data.Group.Source))
                        {
                            <RadzenBadge Text="@data.Group.Source" BadgeStyle="BadgeStyle.Info" IsPill="true" />
                        }
                    </Template>
                </RadzenDataGridColumn>
                <RadzenDataGridColumn TItem="SelectableGroup" Property="Group.UpdateDateTime" Filterable="true" Sortable="true" FormatString="{0:dd/M/yyyy HH:mm:ss}" SortOrder="SortOrder.Descending" Title="@Global.UpdateDateTime" Width="80px" />
                <RadzenDataGridColumn TItem="SelectableGroup" Filterable="false" Sortable="false" FormatString="{0:dd/M/yyyy HH:mm:ss}" Width="80px" TextAlign="TextAlign.Center">
                    <Template Context="data">
                        <SidAuthorizeView Roles=@("/groups/manage")>
                            <Authorized>
                                <RadzenButton Icon="more_vert" Click="@(args => ShowMoreContextMenu(data, args))" />
                            </Authorized>
                        </SidAuthorizeView>
                    </Template>
                </RadzenDataGridColumn>
            </Columns>
        </RadzenDataGrid>
    </Authorized>
    <NotAuthorized>
        @Global.NotAuthorized
    </NotAuthorized>
 </SidAuthorizeView>

@code {
    bool selectAll = false;
    RadzenDataGrid<SelectableGroup> groupsGrid;

    protected override void OnAfterRender(bool firstRender)
    {
        base.OnAfterRender(firstRender);
        if(firstRender)
        {
            SubscribeToAction<RemoveSelectedGroupsSuccessAction>((act) =>
            {
                notificationService.Notify(new NotificationMessage { Severity = NotificationSeverity.Success, Summary = Global.SelectedGroupsRemoved });
                StateHasChanged();
            });
            SubscribeToAction<AddGroupSuccessAction>(async (act) =>
            {
                notificationService.Notify(new NotificationMessage { Severity = NotificationSeverity.Success, Summary = Global.GroupAdded });
                dialogService.Close();
            });
            if (!searchGroupsState.Value.IsLoading)
                groupsGrid?.Reload();
        }
    }

    void LoadData(LoadDataArgs args)
    {
        var act = new SearchGroupsAction { Filter = args.Filter, OrderBy = args.OrderBy, Skip = args.Skip, Take = args.Top };
        dispatcher.Dispatch(act);
    }

    void ShowMoreContextMenu(SelectableGroup group, MouseEventArgs args)
    {
        contextMenuService.Open(args, new List<ContextMenuItem>
        {
            new ContextMenuItem { Text = Global.Delete, Value = 1 }
        }, (a) => {
            if (a.Value.Equals(1))
            {
                var fullPathLst = searchGroupsState.Value.Groups?.Where(c => c.IsSelected).Select(c => c.Group.FullPath)?.ToList();
                var act = new RemoveSelectedGroupsAction { FullPathLst = fullPathLst };
                dispatcher.Dispatch(act);
                contextMenuService.Close();
            }
        });
    }

    void ToggleChanged(bool isSelected, SelectableGroup group)
    {
        var act = new ToggleGroupSelectionAction { IsSelected = isSelected, GroupId = group.Group.Id };
        dispatcher.Dispatch(act);
    }

    void ToggleAll(bool isSelected)
    {        
        var act = new ToggleAllGroupSelectionAction { IsSelected = isSelected };
        dispatcher.Dispatch(act);
    }

    void RowRender(RowRenderEventArgs<SelectableGroup> row)
    {
        const string className = "class";
        if (row.Data.IsNew)
            row.Attributes.Add(className, "new");
        else if (row.Data.IsSelected)
            row.Attributes.Add(className, "active");
        else if (row.Attributes.ContainsKey(className))
            row.Attributes.Remove(className);
    }

    async void AddGroup()
    {
        await dialogService.OpenAsync<AddGroupDialog>(Global.AddGroup, new Dictionary<string, object>(), new DialogOptions
        {
            Width = "700px",
            Height ="512px",
            Resizable = true,
            Draggable = true
        });
    }
}